package org.xx.armory.logback;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.AbstractMatcherFilter;
import ch.qos.logback.core.spi.FilterReply;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;

/**
 * 使用Mark来判断是否输出日志的过滤器。
 */
public class MarkerFilter
        extends AbstractMatcherFilter<ILoggingEvent> {
    private Marker markerToMatch;

    @Override
    public FilterReply decide(
            ILoggingEvent event
    ) {
        if (!isStarted()) {
            return FilterReply.NEUTRAL;
        }

        final var marker = event.getMarker();

        if (marker == null) {
            return this.onMismatch;
        }

        if (marker.contains(markerToMatch)) {
            return this.onMatch;
        } else {
            return this.onMismatch;
        }
    }

    /**
     * 设置需要匹配的Marker。
     *
     * @param markerStr
     *         需要匹配的Marker。
     */
    public void setMarker(
            String markerStr
    ) {
        if (markerStr != null) {
            this.markerToMatch = MarkerFactory.getMarker(markerStr);
        }
    }
}
